package io.eyer.nio.core.event;

import io.eyer.nio.core.support.LifeCycle;
import org.slf4j.Logger;

import java.io.IOException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * Created by 青木 on 2015/8/28.
 */
public abstract class NioAbstract<E> extends Thread implements LifeCycle {

    protected boolean started = false;
    protected Selector selector;
    protected ReactorPool reactorPool;
    protected Queue<E> registeredQueue = new ConcurrentLinkedQueue<>();

    public NioAbstract() throws IOException {
        this.selector = Selector.open();
    }

    public NioAbstract(ReactorPool reactorPool) throws IOException {
        this();
        this.reactorPool = reactorPool;
    }

    @Override
    public void run() {
        this.started = true;
        try {
            this.doRun(this.selector);
        } catch (Exception e) {
            this.close();
            getLogger().error(e.getMessage(), e);
        }
    }


    public void doRun(Selector selector) throws IOException {
        while (isStarted()) {
            selector.select();
            handleRegisteredQueue(selector);
            Set<SelectionKey> selectionKeys = this.selector.selectedKeys();
            selectionKeys.forEach(this::handleKey);
            selectionKeys.clear();
        }
    }

    private void handleRegisteredQueue(Selector selector) {
        E e = null;
        while ((e = this.registeredQueue.poll()) != null) {
            try {
                this.handleRegistered(e, selector);
            } catch (ClosedChannelException e1) {
                getLogger().error(e1.getMessage(), e1);
            }
        }
    }

    @Override
    public void close() {
        try {
            this.started = false;
            this.selector.close();
            this.reactorPool.close();
        } catch (Exception e) {
            getLogger().error(e.getMessage(), e);
        }
    }

    @Override
    public boolean isStarted() {
        return started;
    }

    public abstract Logger getLogger();

    protected abstract void handleRegistered(E e, Selector selector) throws ClosedChannelException;

    public abstract void handleKey(SelectionKey key);

}
